﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Data.SqlTypes;

using System.Drawing;
using System.Data.Linq;
using System.IO;
using System.Web.Mvc;

namespace SpyApp.Models.BaseCommon
{
    /// <summary>
    /// SpyApp.Models.BaseCommon.ConvertUtils class
    /// </summary>    
    public class ConvertUtils
    {
        public static string ToString(string Value)
        {
            return (Value != null) ? Value.Trim() : String.Empty;
        }

        public static string ToString(Object Value)
        {
            return (Value != null) ? Value.ToString() : String.Empty;
        }

        public static double ToDouble(object value)
        {
            if (value is DBNull)
                return 0;
            return Convert.ToDouble(value);
        }

        public static int ToInt32(object value)
        {
            if (value is DBNull)
                return 0;
            return Convert.ToInt32(value);
        }

        public static long ToLong(object value)
        {
            if (value is DBNull)
                return 0;
            return Convert.ToInt64(value);
        }

        public static DateTime? ToDateTime(Object value)
        {
            if (value != null && value.ToString() != String.Empty)
                return Convert.ToDateTime(value);
            return null;
        }

        public static bool ToBoolean(Object value)
        {
            if (value is DBNull)
                return false;
            return Convert.ToBoolean(value);
        }

        //Ham chuyen doi ve chuoi khong dau
        public static string ConvertToUnSign(string text)
        {
            text = text.Trim();
            for (int i = 33; i < 48; i++)
            {
                text = text.Replace(((char)i).ToString(), "");
            }

            /*for (int i = 58; i < 65; i++)
            {
                text = text.Replace(((char)i).ToString(), "");
            }*/

            //ASCII ":" 58
            for (int i = 58; i < 65; i++)
            {
                text = text.Replace(((char)i).ToString(), "");
            }

            for (int i = 91; i < 97; i++)
            {
                text = text.Replace(((char)i).ToString(), "");
            }

            for (int i = 123; i < 127; i++)
            {
                text = text.Replace(((char)i).ToString(), "");
            }

            //text = text.Replace(" ", "-"); //Comment l?i d? không dua kho?ng tr?ng thành ký t? -

            Regex regex = new Regex(@"\p{IsCombiningDiacriticalMarks}+");
            string strFormD = text.Normalize(System.Text.NormalizationForm.FormD);
            return regex.Replace(strFormD, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');
        }

        public static string ConvertDatetimeToStringSQLDatetime(DateTime datetime)
        {
            return datetime.ToString("yyyy-MM-dd");
        }

        //Ham chuyen doi chuoi dinh dang sang ngay dd/MM/yyyy
        public static DateTime ConvertStringToShortDate(string pDatetimeStr)
        {
            try
            {
                pDatetimeStr = pDatetimeStr.Trim();
                if (pDatetimeStr != "")
                {
                    IFormatProvider theCultureInfo = new System.Globalization.CultureInfo("en-GB", true);
                    DateTime result = DateTime.ParseExact(pDatetimeStr, "dd/MM/yyyy", theCultureInfo);
                    return result;
                }
                else
                    return SqlDateTime.MinValue.Value;
            }
            catch
            {
                return DateTime.Now.Date;
            }
        }

        //Ham chuyen doi chuoi dinh dang sang ngay dd/MM/yyyy hh:mm:ss
        public static DateTime ConvertStringToLongDate(string pDatetimeStr)
        {
            try
            {
                pDatetimeStr = pDatetimeStr.Trim();
                if (pDatetimeStr != "")
                {
                    IFormatProvider theCultureInfo = new System.Globalization.CultureInfo("en-GB", true);
                    DateTime result = DateTime.ParseExact(pDatetimeStr, "MM/dd/yyyy HH:mm:ss", theCultureInfo);
                    return result;
                }
                else
                    return SqlDateTime.MinValue.Value;
            }
            catch
            {
                return DateTime.Now;
            }
        }
        public static DateTime ConvertStringToLongDateReport(string pDatetimeStr)
        {
            try
            {
                pDatetimeStr = pDatetimeStr.Trim();
                if (pDatetimeStr != "")
                {
                    IFormatProvider theCultureInfo = new System.Globalization.CultureInfo("en-GB", true);
                    DateTime result = DateTime.ParseExact(pDatetimeStr, "dd/MM/yyyy HH:mm:ss", theCultureInfo);
                    return result;
                }
                else
                    return SqlDateTime.MinValue.Value;
            }
            catch
            {
                return DateTime.Now;
            }
        }
        public static DateTime ConvertStringToLongDateForSearch(string pDatetimeStr)
        {
            try
            {
                pDatetimeStr = pDatetimeStr.Trim();
                if (pDatetimeStr != "")
                {
                    IFormatProvider theCultureInfo = new System.Globalization.CultureInfo("en-GB", true);
                    DateTime result = DateTime.ParseExact(pDatetimeStr, "MM/dd/yyyy HH:mm:ss", theCultureInfo);
                    return result;
                }
                else
                    return SqlDateTime.MinValue.Value;
            }
            catch
            {
                return DateTime.Now;
            }
        }
        public static IFormatProvider DatetimeFormatCustom()
        {
            System.Globalization.CultureInfo tem = new System.Globalization.CultureInfo("en-GB", true);
            tem.DateTimeFormat.FullDateTimePattern = "dd/MM/yyy hh:mm:ss";
            return tem;
        }



        #region Nghia
        public static double toDouble(string value)
        {
            double temp = 0;
            double.TryParse(value, out temp);
            return temp;
        }

        /// <summary>
        /// String to Int32
        /// </summary>
        /// <param name="value">String value</param>
        /// <param name="valueIfFalse">Value Return if null value</param>
        /// <returns></returns>
        public static int ToInt32(string value, int valueIfFalse = 0)
        {
            int temp = 0;
            if (int.TryParse(value, out temp))
                return temp;
            return valueIfFalse;
        }

        public static long ToLong(string value)
        {
            long temp = 0;
            long.TryParse(value, out temp);
            return temp;
        }

        /// <summary> Chuyển Image thành Binary </summary>
        public static Binary Image_to_Binary(Image image)
        {
            if (image != null)
            {
                MemoryStream stream = new MemoryStream();
                image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                return stream.ToArray();
            }
            else return null;
        }

        /// <summary> Chuyển Binary trở lại Image </summary>
        public static Image Binary_to_Image(Binary binary)
        {
            if (binary != null && binary != new Binary(new byte[0]))
            {
                MemoryStream stream = new MemoryStream(binary.ToArray());
                Image img = Image.FromStream(stream);
                return img;
            }
            else return null;
        }

        /// <summary> resize image </summary>
        public static Image ResizeImage(Image imgToResize, int maxWidth, int maxHeight)
        {
            // canh lại maxHeight
            int resizeWidth = imgToResize.Width;
            int resizeHeight = imgToResize.Height;
            double aspect = (double)resizeWidth / resizeHeight;

            if (resizeWidth > maxWidth)
            {
                resizeWidth = maxWidth;
                resizeHeight = (int)(resizeWidth / aspect);
            }
            if (resizeHeight > maxHeight)
            {
                aspect = (double)resizeWidth / resizeHeight;
                resizeHeight = maxHeight;
                resizeWidth = (int)(resizeHeight * aspect);
            }
            Size size = new Size(resizeWidth, resizeHeight);
            Bitmap bitmap = new Bitmap(imgToResize, size);
            return (Image)bitmap;
        }

        /// <summary> Xóa 0, 84, +84 của số điện thoại </summary>
        public static string removeCountryPhone(string value)
        {
            value = value.Trim();
            try
            {
                if (value.Substring(0, 1).Equals("0"))
                {
                    value = value.Remove(0, 1);
                }
                else if (value.Substring(0, 3).Equals("+84"))
                {
                    value = value.Remove(0, 3);
                }
                else if (value.Substring(0, 2).Equals("84"))
                {
                    value = value.Remove(0, 2);
                }
                return value;
            }
            catch
            {
                return value;
            }
        }

        /// <summary> chuyển từ FullName sang ... Họ + tên lót + tên </summary>
        public static void ToName(string _fullName, ref string _firstName, ref string _middleName, ref string _lastName)
        {
            _fullName = _fullName.Trim();
            if (_fullName != string.Empty)
            {
                List<string> listName = (_fullName.Split(' ')).ToList();
                // xóa array rỗng
                listName = listName.Where(item => !string.IsNullOrEmpty(item)).ToList();
                if (listName.Count() > 0)
                {
                    _firstName = listName.First();  // tên đầu
                    _lastName = listName.Last();    // tên cuối

                    if (listName.Count() > 0)
                        listName.Remove(listName.First());
                    if (listName.Count() > 0)
                        listName.Remove(listName.Last());

                    _middleName = string.Join(" ", listName.ToArray()); // tên giữa
                }
            }
        }

        public static string ToGenderText(bool? value)
        {
            try
            {
                string returnText = string.Empty;
                switch (value)
                {
                    case true:
                        returnText = "Nam";
                        break;
                    case false:
                        returnText = "Nữ";
                        break;
                    case null:
                        returnText = "Không xác định";
                        break;
                    default:
                        returnText = "Không xác định";
                        break;
                }
                return returnText;
            }
            catch
            {
                return "";
            }
        }

        /// <summary> chuyển string có kí tự đặc biệt enter /n/r thành | </summary>
        public static string SpecialChar2String(string value)
        {
            return value.Replace("\r\n", "|").Replace("\n", "|");
        }

        /// <summary>Chuyển Enum to list
        /// Using: EnumToSelectList(typeof(enum))  
        /// </summary>
        public static SelectList EnumToSelectList(Type enumType)
        {
            List<SelectListItem> listItem = EnumToSelectListItem(enumType);
            System.Web.Mvc.SelectList selectList = new System.Web.Mvc.SelectList(listItem, "Value", "Text");
            return selectList;
        }

        /// <summary>Chuyển Enum to list
        /// Using: EnumToSelectList(typeof(enum))  
        /// </summary>
        public static List<SelectListItem> EnumToSelectListItem(Type enumType)
        {
            List<SelectListItem> listItem = new List<SelectListItem>();

            string[] names = System.Enum.GetNames(enumType);
            foreach (string name in names)
            {
                string desciption = EnumUtils.stringValueOf((System.Enum)System.Enum.Parse(enumType, name));
                listItem.Add(new SelectListItem()
                {
                    Text = desciption,
                    Value = desciption
                });
            }
            return listItem;
        }
        #endregion
        
        //Hàm tạo uuid cho sms
        public static string CreateUuidForSMS(DateTime dateTime,string phoneNum, string type)
        {
            string _uuid = "";
            _uuid = dateTime.ToString("MMddyyyy-HHmmss") + "-" + phoneNum + "-" + type;
            return _uuid;
        }
        
    }

}
